package com.zliblike_platform.service.impl;

import com.zliblike_platform.entity.Category;
import com.zliblike_platform.mapper.CategoryMapper;
import com.zliblike_platform.service.CategoryService;
import com.zliblike_platform.vo.CategoryVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 图书分类服务实现类
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryVO> getAllCategories() {
        List<Category> categories = categoryMapper.selectAll();
        return categories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<CategoryVO> getCategoryTree() {
        // 获取所有分类
        List<Category> allCategories = categoryMapper.selectAll();
        
        // 转换为VO对象
        List<CategoryVO> categoryVOs = allCategories.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
        
        // 构建分类树
        Map<Long, List<CategoryVO>> childrenMap = new HashMap<>();
        
        // 按父ID分组
        for (CategoryVO categoryVO : categoryVOs) {
            Long parentId = categoryVO.getParentId();
            if (!childrenMap.containsKey(parentId)) {
                childrenMap.put(parentId, new ArrayList<>());
            }
            childrenMap.get(parentId).add(categoryVO);
        }
        
        // 获取顶级分类
        List<CategoryVO> rootCategories = childrenMap.getOrDefault(0L, Collections.emptyList());
        
        // 递归设置子分类
        for (CategoryVO categoryVO : categoryVOs) {
            Long categoryId = categoryVO.getCategoryId();
            List<CategoryVO> children = childrenMap.getOrDefault(categoryId, Collections.emptyList());
            if (!children.isEmpty()) {
                categoryVO.setHasChildren(true);
                categoryVO.setChildren(children);
            } else {
                categoryVO.setHasChildren(false);
            }
        }
        
        return rootCategories;
    }

    @Override
    public CategoryVO getCategoryById(Long categoryId) {
        Category category = categoryMapper.selectById(categoryId);
        if (category == null) {
            return null;
        }
        return convertToVO(category);
    }

    @Override
    @Transactional
    public void addCategory(Category category) {
        // 设置创建时间和更新时间
        LocalDateTime now = LocalDateTime.now();
        category.setCreateTime(now);
        category.setUpdateTime(now);
        
        // 如果未设置父ID，默认为0（顶级分类）
        if (category.getParentId() == null) {
            category.setParentId(0L);
        }
        
        // 如果未设置层级，则根据父分类层级+1
        if (category.getLevel() == null) {
            if (category.getParentId() == 0L) {
                // 顶级分类
                category.setLevel(1);
            } else {
                // 子分类，父分类层级+1
                Category parentCategory = categoryMapper.selectById(category.getParentId());
                if (parentCategory != null) {
                    category.setLevel(parentCategory.getLevel() + 1);
                } else {
                    category.setLevel(1);
                }
            }
        }
        
        categoryMapper.insert(category);
    }

    @Override
    @Transactional
    public void updateCategory(Category category) {
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.updateById(category);
    }

    @Override
    @Transactional
    public void deleteCategory(Long categoryId) {
        // 检查是否有关联的书籍
        Integer bookCount = categoryMapper.countBooksByCategory(categoryId);
        if (bookCount > 0) {
            throw new RuntimeException("该分类下有关联书籍，无法删除");
        }
        
        categoryMapper.deleteById(categoryId);
    }
    
    /**
     * 将Category实体转换为CategoryVO
     * @param category 分类实体
     * @return 分类VO
     */
    private CategoryVO convertToVO(Category category) {
        if (category == null) {
            return null;
        }
        
        CategoryVO vo = new CategoryVO();
        BeanUtils.copyProperties(category, vo);
        
        // 获取分类下的书籍数量
        Integer bookCount = categoryMapper.countBooksByCategory(category.getCategoryId());
        vo.setBookCount(bookCount);
        
        return vo;
    }
} 